import { request } from "@/utils/request";
import type { ResponseData } from "@/utils/request";

// 抄经会话响应接口，根据实际API返回格式定义
export interface CopySessionResponse {
  detailId: number;
  volumeChapterName: string;
  currentLineIndex: number;
  currentLineContent: string;
  totalLines: number;
  completeLines: number;
  complete: number;
  pinyinWithCharacterPairs: [string, string][];
  totalVolumes?: number;  // 添加总卷数字段
  title?: string;        // 添加标题字段
  volume?: number;       // 添加当前卷数字段
}

// 抄经提交结果接口
export interface CopyCompleteResult {
  success: boolean;
  meritPoints?: number;
  message?: string;
  rawResponse?: any; // 添加原始响应字段
}

// 经文内容接口
export interface ScriptureContentResponse {
  contentId: number;
  title: string;
  volume: number;
  totalVolumes: number;
  content: string;
  pinyinPairs?: {
    pinyin: string;
    character: string;
  }[];
}

// 经文详情接口
export interface ScriptureDetailResponse {
  id: number;
  scriptureId: number;
  volumeChapter: number;
  volumeChapterName: string;
  contentId?: number;
  createTime?: string;
  updateTime?: string;
}

// 通用API响应接口，兼容msg和message字段
interface ApiResponse extends Partial<ResponseData<any>> {
  code?: number;
  data?: any;
  message?: string;
  msg?: string; // 有些API返回msg而不是message
}

/**
 * 获取抄经会话内容
 * @param detailId 经文详情ID
 * @returns 抄经会话数据
 */
export const fetchCopySession = async (detailId: number): Promise<CopySessionResponse> => {
  try {
    console.log('请求抄经会话，详情ID:', detailId);
    
    const rawResponse = await request.post('/scripture/copy/session', {
      detailId: detailId
    });
    
    // 将响应断言为ApiResponse类型
    const response = rawResponse as unknown as ApiResponse;
    
    console.log('抄经会话原始响应:', response);
    
    // 获取错误消息，兼容msg和message
    const errorMessage = response.msg || response.message;
    
    // 如果返回的是未登录错误，显示登录框
    if (response.code === 500 && errorMessage && errorMessage.includes('请登录')) {
      console.error('抄经会话请求需要登录:', response);
      
      // 显示登录确认框
      uni.showModal({
        title: '提示',
        content: '请先登录后继续抄经',
        confirmText: '去登录',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/login/index'
            });
          } else {
            uni.navigateBack();
          }
        }
      });
      
      throw response; // 保持原有的错误抛出逻辑
    }
    
    if (response.code === 200 && response.data) {
      console.log('抄经会话响应:', response);
      return response.data as CopySessionResponse;
    } else {
      // 保留原始错误信息
      const error = new Error(errorMessage || '获取抄经内容失败');
      // 附加额外信息，便于调用方识别错误类型
      (error as any).code = response.code;
      (error as any).msg = errorMessage;
      (error as any).data = response;
      throw error;
    }
  } catch (error) {
    console.error('获取抄经会话失败:', error);
    // 直接抛出错误，让调用方处理
    throw error;
  }
};

/**
 * 获取经文内容
 * @param contentId 内容ID
 * @returns 经文内容数据
 */
export const fetchScriptureContent = async (contentId: number): Promise<ScriptureContentResponse> => {
  try {
    console.log('请求经文内容，内容ID:', contentId);
    
    const rawResponse = await request.get('/scripture/content', {
      data: { contentId }
    });
    
    // 将响应断言为ApiResponse类型
    const response = rawResponse as unknown as ApiResponse;
    
    console.log('经文内容原始响应:', response);
    
    // 获取错误消息，兼容msg和message
    const errorMessage = response.msg || response.message;
    
    // 如果返回的是未登录错误，直接抛出完整响应
    if (response.code === 500 && errorMessage && errorMessage.includes('请登录')) {
      console.error('经文内容请求需要登录:', response);
      throw response; // 直接抛出原始响应对象
    }
    
    if (response.code === 200 && response.data) {
      console.log('经文内容响应:', response);
      return response.data as ScriptureContentResponse;
    } else {
      // 保留原始错误信息
      const error = new Error(errorMessage || '获取经文内容失败');
      // 附加额外信息，便于调用方识别错误类型
      (error as any).code = response.code;
      (error as any).msg = errorMessage;
      (error as any).data = response;
      throw error;
    }
  } catch (error) {
    console.error('获取经文内容失败:', error);
    // 直接抛出错误，让调用方处理
    throw error;
  }
};

/**
 * 获取经文详情章节
 * @param scriptureId 经文ID
 * @returns 经文详情数据
 */
export const fetchScriptureDetails = async (scriptureId: number): Promise<ScriptureDetailResponse[]> => {
  try {
    console.log('请求经文详情，经文ID:', scriptureId);
    
    const rawResponse = await request.get('/scripture/detail/scriptureId', {
      data: { scriptureId }
    });
    
    // 将响应断言为ApiResponse类型
    const response = rawResponse as unknown as ApiResponse;
    
    // 获取错误消息，兼容msg和message
    const errorMessage = response.msg || response.message;
    
    if (response.code === 200 && response.data) {
      console.log('经文详情响应:', response);
      return response.data as ScriptureDetailResponse[];
    } else {
      // 保留原始错误信息
      const error = new Error(errorMessage || '获取经文详情失败');
      // 附加额外信息，便于调用方识别错误类型
      (error as any).code = response.code;
      (error as any).msg = errorMessage;
      (error as any).data = response;
      throw error;
    }
  } catch (error) {
    console.error('获取经文详情失败:', error);
    // 直接抛出错误，让调用方处理
    throw error;
  }
};

/**
 * 根据经文ID和卷数查找对应的内容ID
 * @param scriptureId 经文ID
 * @param volume 卷数
 * @returns 找到的内容ID，未找到则返回undefined
 */
export const findContentIdByVolume = async (scriptureId: number, volume: number): Promise<number | undefined> => {
  try {
    const details = await fetchScriptureDetails(scriptureId);
    const volumeDetail = details.find(detail => 
      detail.volumeChapter === volume || 
      detail.volumeChapterName?.includes(`${volume}`)
    );
    
    return volumeDetail?.contentId;
  } catch (error) {
    console.error('查找卷数对应内容ID失败:', error);
    throw error;
  }
};

/**
 * 提交抄经结果
 * @param detailId 经文详情ID
 * @param content 抄写的内容
 * @param lineIndex 行索引，默认为0
 * @returns 提交结果
 */
export const submitCopyResult = async (
  detailId: number,
  content: string,
  lineIndex: number = 0
): Promise<CopyCompleteResult> => {
  try {
    if (!detailId || !content) {
      throw new Error('缺少必要参数');
    }
    
    console.log('提交抄经内容，详情ID:', detailId, '内容:', content, '行索引:', lineIndex);
    
    // 构建请求体
    const requestBody = {
      detailId,
      copyText: content,
      lineIndex,
      userId: uni.getStorageSync('userId') || 0 // 从本地存储获取用户ID，如果没有则默认为0
    };
    
    // 使用POST方法提交JSON数据
    const rawResponse = await request.post('/scripture/copy/sumit', requestBody);
    
    // 将响应断言为ApiResponse类型
    const response = rawResponse as unknown as ApiResponse;
    
    console.log('抄经提交原始响应:', response);
    
    // 获取错误消息，兼容msg和message
    const errorMessage = response.msg || response.message;
    
    // 如果返回的是未登录错误，直接抛出完整响应
    if (response.code === 500 && errorMessage && errorMessage.includes('请登录')) {
      console.error('抄经提交需要登录:', response);
      throw response; // 直接抛出原始响应对象
    }
    
    if (response.code === 200) {
      console.log('抄经提交成功:', response);
      
      // 从响应中获取更多信息
      const meritEarn = response.data?.meritEarn || 1;
      const feedback = response.data?.feedback || '提交成功';
      
      return {
        success: true,
        meritPoints: meritEarn,
        message: feedback,
        rawResponse: response // 返回原始响应
      };
    } else {
      // 创建包含原始错误信息的错误对象
      const error = new Error(errorMessage || '提交失败');
      // 附加额外信息，便于调用方识别错误类型
      (error as any).code = response.code;
      (error as any).msg = errorMessage;
      (error as any).data = response;
      throw error;
    }
  } catch (error) {
    console.error('提交抄经结果失败:', error);
    
    // 如果是API响应错误，直接抛出以便调用方可以检查错误类型
    if ((error as any).code || (error as any).msg || (error as any).data) {
      throw error;
    }
    
    // 其他类型的错误，返回一个通用的失败结果
    return {
      success: false,
      message: error instanceof Error ? error.message : '提交失败，请重试'
    };
  }
};
